//
//  GamePlayScene.m
//  jumpingfrog
//
//  Created by Tri Vo on 8/16/13.
//  Copyright 2013 Tri Vo. All rights reserved.
//

#import "GamePlayScene.h"
#import "GeneralDef.h"
#import "GameController.h"
#import "MenuScene.h"
#import "ResourcesManager.h"
#import "CustomSpriteWithTouch.h"
#import "SceneManager.h"
#import "CFIle.h"
#include <stdio.h>
#import "CUtil.h"

@implementation GamePlayScene
@synthesize m_pFrog;
@synthesize m_jumpAction;
@synthesize m_moveAction;

#pragma mark - Scene Init & Memory Management Methods

+ (CCScene *) scene {
    CCScene *pScene = [CCScene node];
    GamePlayScene *pLayer = [GamePlayScene node];
    CCScene *pRunningScene = [[CCDirector sharedDirector] runningScene];
    [pRunningScene removeAllChildrenWithCleanup:YES];
    [pScene addChild:pLayer];
    return pScene;
}

- (id)init {
    if (self = [super init]) {
        m_winSize = [GameController getWinSize];
        [self initScreen];
        m_timer = [[CTImer alloc] init];
        m_seconds = 0;
        [self scheduleUpdate];
    }
    return self;
}

- (void)onEnter {
    [super onEnter];
//    [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:(INT_MIN + 1) swallowsTouches:YES];
}

- (void)onEnterTransitionDidFinish {
    [super onEnterTransitionDidFinish];
}

- (void)onExit {
    [super onExit];
//    [[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
}

- (void)onExitTransitionDidStart {
    [super onExitTransitionDidStart];
}

- (void)dealloc {
    [m_timer release];
    m_timer = nil;
    CCLabelTTF *pLblSecondsPassed = (CCLabelTTF *)[self getChildByTag:TAG_LABEL_SECONDPASSED];
    if (pLblSecondsPassed != nil) {
        [pLblSecondsPassed release];
        pLblSecondsPassed = nil;
    }
    
    if (m_subMenuForSettings != nil) {
        [m_subMenuForSettings release];
        m_subMenuForSettings = nil;
    }
    
    if (m_subMenu != nil) {
        [m_subMenu release];
        m_subMenu = nil;
    }
    
    if (m_blackBackground != nil) {
        [m_blackBackground release];
        m_blackBackground = nil;
    }
    [super dealloc];
}

#pragma mark - Touch methods

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    return YES;
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
//    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
//    CGSize winSize = [GameController getWinSize];
    
    
}
#pragma mark - Scene Methods

- (void) initFrog {
    CGSize winSize = [GameController getWinSize];
    NSMutableArray *pFrameArr = [[NSMutableArray alloc] init];
    
    for (int i = 1; i <= 7; i++) {
        NSString *pFrameName = [NSString stringWithFormat:@"frog%d.png", i];
        CCSpriteFrame *pFrame = [[[ResourcesManager getInstance] getSharedFrameCache] spriteFrameByName:pFrameName];
        [pFrameArr addObject:pFrame];
    }
    
    CCAnimation *pJumpingAnimation = [CCAnimation animationWithSpriteFrames:pFrameArr delay:0.1f];
    
    self.m_jumpAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:pJumpingAnimation]];
    
    // Add Sprite Sheet
    CCSpriteBatchNode *pSpriteSheetForFrog = [[ResourcesManager getInstance] getSpriteSheetForFrog];
    [self addChild:pSpriteSheetForFrog];
    
    // Init frog
    self.m_pFrog = [CCSprite spriteWithSpriteFrameName:SPRITE_FRAME_FROG_BEGIN];
    [m_pFrog setPosition:CGPointMake(winSize.width/2, winSize.height/2)];
    [m_pFrog setScale:0.5f];
    [pSpriteSheetForFrog addChild:m_pFrog];
    
    [m_pFrog runAction:m_jumpAction];
    
}

- (void) initLeaves {
    CCSprite *pTotalSprite = [[CCSprite alloc] init];
    [pTotalSprite setPosition:CGPointMake(m_winSize.width/2, m_winSize.height/2)];
    [self addChild:pTotalSprite];
    
    CGFloat beginX = 30;
    CGFloat beginY = 220;
    CGFloat stepX = 90;
    CGFloat stepY = 70;
    NSArray *lines = [CFIle readFile:@"Map1"];
    for (NSString *line in lines) {
        for (int i = 0; i < line.length; i++) {
            NSString *str = [line substringWithRange:NSMakeRange(i, 1)];
            CCSprite *pSprite = [CUtil getSpriteByCharacter:str];
            [pSprite setAnchorPoint:CGPointZero];
            [pSprite setPosition:CGPointMake(beginX, beginY)];
            [self addChild:pSprite];
            
            [pSprite setScale:0.5f];
            beginX += stepX;
        }
        beginX = 30;
        beginY -= stepY;
    }
}

- (void) initHUD {
    CCScale9Sprite *pBackgroundHUD = [CCScale9Sprite spriteWithSpriteFrameName:SPRITE_HUD_BACKGROUND];
    [pBackgroundHUD setContentSize:CGSizeMake(480, 40)];
    [pBackgroundHUD setPosition:CGPointMake(m_winSize.width/2, 300)];
    [self addChild:pBackgroundHUD];
    
    CCLabelTTF *pLabelLives = [CCLabelTTF labelWithString:STR_LIVES fontName:FONT_CONTENT fontSize:24];
    [pLabelLives setAnchorPoint:CGPointZero];
    [pLabelLives setPosition:ccp(10, 290)];
    [self addChild:pLabelLives];
    
    // Live
    CGFloat stepX = 50;
    CGFloat beginX = 80;
    for (int i = 0; i < [GameController getFrogLife]; i++) {
        CCSprite *pSprite = [CCSprite spriteWithSpriteFrameName:SPRITE_HUD_LIVES];
        [pSprite setAnchorPoint:CGPointZero];
        [pSprite setScale:0.5f];
        [pSprite setPosition:ccp(stepX*i + beginX, 290)];
        [self addChild:pSprite];
    }
    
    // Second label
    CCLabelTTF *pLabelSeconds = [CCLabelTTF labelWithString:STR_SECONDS fontName:FONT_CONTENT fontSize:24];
    [pLabelSeconds setAnchorPoint:CGPointZero];
    [pLabelSeconds setPosition:ccp(340, 290)];
    [self addChild:pLabelSeconds];
    
    // Time second label
    CCLabelTTF *pLabelSecondPassed = [CCLabelTTF labelWithString:@"0" fontName:FONT_CONTENT fontSize:24];
    [pLabelSecondPassed setTag:TAG_LABEL_SECONDPASSED];
    [pLabelSecondPassed setAnchorPoint:CGPointZero];
    [pLabelSecondPassed setPosition:CGPointMake(450, 290)];
    [self addChild:pLabelSecondPassed];
    [pLabelSecondPassed retain];
    
    // Btn back
    CCMenuItemFont *pBtnBack = [CCMenuItemFont itemWithString:STR_MENU target:self selector:@selector(btnMenu_Clicked)];
    [pBtnBack setFontSize:20];
    CCMenu *pMenuBack = [CCMenu menuWithItems:pBtnBack, nil];
    [pMenuBack setPosition:CGPointMake(m_winSize.width/2 + 30, 300)];
    [self addChild:pMenuBack];
    [self setTouchEnabled:YES];
}

- (void) initScreen {
    m_isFrogHorizontal = NO;
    m_isJumping = NO;
    m_isGameRunning = YES;
    // Background
    CCSprite *pSpriteBackground = [CCSprite spriteWithFile:IMG_BACKGROUND];
    [pSpriteBackground setAnchorPoint:CGPointZero];
    [pSpriteBackground setPosition:CGPointZero];
    [self addChild:pSpriteBackground];
    // HUD
    [self initHUD];
    // Init leaf
    [self initLeaves];
}

- (void)update:(ccTime)delta {
    if (m_isGameRunning) {
        [m_timer increaseTime:delta];
        
        CCLabelTTF *pLabelSecondsPassed = (CCLabelTTF *)[self getChildByTag:TAG_LABEL_SECONDPASSED];
        [pLabelSecondsPassed setString:[NSString stringWithFormat:@"%d", [m_timer getSecondsPassed]]];
    }
    
}

- (void) frogMoveEnded {
    [self.m_pFrog stopAllActions];
    m_isJumping = NO;
}

#pragma mark - Scene Actions

- (void) btnBack_Clicked {
    [[SceneManager getInstance] goMenu];
}

- (void) btnBackToMenu_Clicked {
    [m_subMenuForSettings removeFromParentAndCleanup:YES];
    [m_blackBackground removeFromParentAndCleanup:YES];
    [m_subMenuForSettings release];
    m_subMenuForSettings = nil;
    [m_blackBackground release];
    m_blackBackground = nil;
    [m_blackBackground release];
    m_blackBackground = nil;
    [self btnMenu_Clicked];
}

- (void) btnSound_Clicked {
    if ([GameController getSoundState]) {
        [GameController setSoundState:NO];
    } else {
        [GameController setSoundState:YES];
    }
}

- (void) btnMusic_Clicked {
    if ([GameController getMusicState]) {
        [GameController setMusicState:NO];
    } else {
        [GameController setMusicState:YES];
    }
}

- (void) btnResume_Clicked {
    [m_subMenu removeFromParentAndCleanup:YES];
    [m_blackBackground removeFromParentAndCleanup:YES];
    m_isGameRunning = YES;
    [m_subMenu release];
    m_subMenu = nil;
    [m_blackBackground release];
    m_blackBackground = nil;
}

- (void) btnSettings_Clicked {
    [m_subMenu removeFromParentAndCleanup:YES];
    [m_blackBackground removeFromParentAndCleanup:YES];
    [m_subMenu release];
    m_subMenu = nil;
    [m_blackBackground release];
    m_blackBackground = nil;
    
    if (m_blackBackground == nil) {
        m_blackBackground = [[CCSprite alloc] initWithFile:IMG_BLACK_BACKGROUND];
        [m_blackBackground setOpacity:150];
        [m_blackBackground setContentSize:m_winSize];
        [m_blackBackground setPosition:CGPointMake(m_winSize.width/2, m_winSize.height/2)];
    }
    [self addChild:m_blackBackground];
    
    // Menu
    /// Sound
    CCMenuItemFont *pSoundON = [CCMenuItemFont itemWithString:STR_SOUND_ON target:nil selector:nil];
    CCMenuItemFont *pSoundOFF = [CCMenuItemFont itemWithString:STR_SOUND_OFF target:nil selector:nil];
    CCMenuItemToggle *pToggleSound = nil;
    if ([GameController getSoundState]) {
        pToggleSound = [CCMenuItemToggle itemWithTarget:self selector:@selector(btnSound_Clicked) items:pSoundON, pSoundOFF, nil];
    } else {
        pToggleSound = [CCMenuItemToggle itemWithTarget:self selector:@selector(btnSound_Clicked) items:pSoundOFF, pSoundON, nil];
    }
    
    /// Music
    CCMenuItemFont *pMusicON = [CCMenuItemFont itemWithString:STR_MUSIC_ON target:nil selector:nil];
    CCMenuItemFont *pMusicOFF = [CCMenuItemFont itemWithString:STR_MUSIC_OFF target:nil selector:nil];
    CCMenuItemToggle *pToggleMusic = nil;
    if ([GameController getMusicState]) {
        pToggleMusic = [CCMenuItemToggle itemWithTarget:self selector:@selector(btnMusic_Clicked) items:pMusicON, pMusicOFF, nil];
    } else {
        pToggleMusic = [CCMenuItemToggle itemWithTarget:self selector:@selector(btnMusic_Clicked) items:pMusicOFF, pMusicON, nil];
    }

    // Btn Back to menu

    CCMenuItemFont *pBtnBackToMenu = [CCMenuItemFont itemWithString:STR_BACK target:self selector:@selector(btnBackToMenu_Clicked)];
    m_subMenuForSettings = [CCMenu menuWithItems:pToggleMusic, pToggleSound, pBtnBackToMenu, nil];
    [m_subMenuForSettings alignItemsVerticallyWithPadding:10];
    [m_subMenuForSettings setPosition:CGPointMake(m_winSize.width/2, m_winSize.height/2)];
    [self addChild:m_subMenuForSettings];
    [m_subMenuForSettings retain];
}

- (void) btnMenu_Clicked {
    m_isGameRunning = NO;
    if (m_blackBackground == nil) {
        m_blackBackground = [[CCSprite alloc] initWithFile:IMG_BLACK_BACKGROUND];
        [m_blackBackground setOpacity:150];
        [m_blackBackground setContentSize:m_winSize];
        [m_blackBackground setPosition:CGPointMake(m_winSize.width/2, m_winSize.height/2)];
    }
    [self addChild:m_blackBackground];
    
    // Sub menu
    if (m_subMenu == nil) {
        CCMenuItemFont *pMenu_Resume = [CCMenuItemFont itemWithString:STR_RESUME target:self selector:@selector(btnResume_Clicked)];
        CCMenuItemFont *pMenu_Settings = [CCMenuItemFont itemWithString:STR_SETTINGS target:self selector:@selector(btnSettings_Clicked)];
        CCMenuItemFont *pMenu_Quit = [CCMenuItemFont itemWithString:STR_QUIT target:self selector:@selector(btnBack_Clicked)];
        m_subMenu = [[CCMenu alloc] initWithArray:[NSArray arrayWithObjects:pMenu_Resume, pMenu_Settings, pMenu_Quit, nil]];
        [m_subMenu alignItemsVerticallyWithPadding:10];
        [m_subMenu setPosition:CGPointMake(m_winSize.width/2, m_winSize.height/2)];
    }
    [self addChild:m_subMenu];
}

@end
